/**
 * Url处理类
 */
define(function() {
  return function(url) {
    this.href = "";
    this.hash = "";
    this.parameters = {};

    function parseHash(obj, url) {
      var temp = url;
      var pos = url.lastIndexOf('#');
      if (pos > 0) {
        obj.hash = url.substr(pos);
        temp = url.substr(0, pos);
      }
      return temp;
    }

    function parseParameters(obj, url) {
      var urlTemp = url;
      var paraStart = urlTemp.indexOf('?');
      var paraArrays = [];
      if (paraStart >= 0) {
        var search = urlTemp.substr(paraStart);
        if (search && search.length > 1) {
          paraArrays = search.substr(1).split('&');
          for ( var i in paraArrays) {
            var kv = paraArrays[i].split('=');
            var k = kv[0];
            var v = kv[1];
            obj.parameters[k] = v;
          }
        }
        urlTemp = urlTemp.substr(0, paraStart);
      }
      return urlTemp;
    }

    var urlTemp;
    if (!(url && url.length > 1)) {
      urlTemp = window.location.href;
    } else {
      urlTemp = url;
    }

    urlTemp = parseHash(this, urlTemp);
    this.href = parseParameters(this, urlTemp);

    this.setParam = function(name, val) {
      this.parameters[name] = val;
    };

    // 获取Url中的参数
    this.getParam = function(name) {
      var val = this.parameters[name];
      if (val) {
        return unescape(this.parameters[name]);
      } else {
        return null;
      }
    };

    this.getSearchString = function() {
      var result = "";
      for ( var p in this.parameters) {
        result = result + '&' + p + '=' + this.parameters[p];
      }
      if (result.length > 1 && result.charAt(0) == '&') {
        result = '?' + result.substr(1);
      }
      return result;
    }

    this.toString = function() {
      return this.href + this.getSearchString() + this.hash;
    }
  }
});